import 'dart:io';

import 'package:dart_vlc/dart_vlc.dart';
import 'package:file_picker/file_picker.dart';
import 'package:get/get.dart';
import 'package:palyer/app/components/toast_widget.dart';
import 'package:palyer/app/core/utils/log_util.dart';
import 'package:palyer/app/modules/player/player/states.dart';


class PlayerController extends GetxController {
  final PlayerStates states = PlayerStates();

  Player player = Player(id: 0);

  Playlist playlist = Playlist(
    medias: [
      Media.file(File('C:/Users/Administrator/Videos/mp4/6_70e14f88f250f903404c9d2f65f8114a_0.mp4')),
    ],
  );

  // 初始化
  @override
  void onInit() {
    super.onInit();
    player.open(playlist);
    player.play();
  }

  // 遍历文件夹
  traverseFolders(String url) {
    Directory directory = Directory(url);
    List<FileSystemEntity> children = directory.listSync();
    for (final FileSystemEntity in children) {
      print(FileSystemEntity.path.replaceAll('\\', '/'));
      playlist.medias.add(Media.file(
          File(FileSystemEntity.path.replaceAll('\\', '/').toString())));
    }
    player.open(playlist);
    player.play();
  }

  openFile(List<File> files) {
    for (var i in files) {
      String url = i.path.replaceAll('\\', '/').toString();
      AppLogger.devLog(url);
      playlist.medias.add(Media.file(File(url)));
    }
    player.open(playlist);
    player.play();
  }

  // 文件选取
  selectFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      allowedExtensions: [
        'mp4',
        'mp3',
        'avi',
      ],
      dialogTitle: '你爸爸在选文件',
      allowMultiple: true,
    );
    if (result != null) {
      List<File> files = result.paths.map((path) => File(path!)).toList();
      openFile(files);
    } else {
      // User canceled the picker
      AppToast.show('为选取文件',);
    }
  }

  @override
  void onClose() {
    player.stop();
    player.dispose();
    playlist.medias.clear();
    super.onClose();
  }


}
